package com.huan.servlet.user;

import com.huan.pojo.User;
import com.huan.service.user.UserService;
import com.huan.service.user.UserServiceImpl;
import com.huan.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * 作者： 王鹏欢
 * @Date 2021-07-19 21:32
 * @Description TODO
 */
public class LoginServlet extends HttpServlet {
    //和数据库中的密码对比，调用业务层
    UserService userService = new UserServiceImpl();

    //Servlet 控制层调用业务层代码
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        System.out.println("进入LoginServlet...");

        //增加操作
        //获取用户名和密码
        String userCode = req.getParameter("usercode");
        String userPassword = req.getParameter("password");

        User user = userService.login(userCode, userPassword);//这里已经把登录的人查了出来

        if (null != user && user.getUserPassword().equals(userPassword)) {//查有此人可以登录
            //将用户的信息放到Session里
            req.getSession().setAttribute(Constants.USER_SESSION, user);
            req.getSession().setAttribute("userList", userList);
            //跳转到内部主页
            resp.sendRedirect("index.jsp");
        } else {//查无此人无法登录
            //返回登录页面
            req.setAttribute("errorMsg", "用户名或者密码有误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        doGet(req, resp);
    }
}
